from flask import g
from flask import request, jsonify
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.captcha.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
from flask import render_template,current_app

# 访问首页时返回数据和摸板
@index_blue.route('/',methods=["GET",'POST'])
@user_login_data
def index():

    # 从ｎｅｗｓ表中取出点击量前十的内容
    try:
        news_items = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 把取出的列表改成包含字典数据的列表
    click_news_list = []
    for new in news_items:
        click_news_list.append(new.to_dict())

    try:
        categories = Category.query.all()

    except Exception as e:
        current_app.logger.error(e)

    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())


    # 拼接数据,渲染到页面中
    data = {
        # 如果user有值返回左边内容, 如果没有值返回右边内容
        "user_info": g.user.to_dict() if g.user else None,
        'click_news_list':click_news_list,
        'categories_list':categories_list
    }
    return render_template('news/index.html',data = data)

# 返回页面图标
@index_blue.route('/favicon.ico')
def favicon_ico():
    print('sddsa')
    return current_app.send_static_file('news/favicon.ico')

@index_blue.route('/newslist')
def newslist():

    # 获取参数
    # 1.1　cid　是分类的ｉｄ　决定查询数据的类型，
    # 后面的数字是如果没有获取到则默认是１
    cid = request.args.get("cid", 1)
    # 决定了第几页
    page = request.args.get("page", 1)
    # 1.2 决定了一页多少个
    per_page = request.args.get("per_page", 10)
    # 转换参数类型
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10


    a_list = []
    if cid != '1':
        a_list.append(News.category_id == cid)
    # 查询数据库
    paginate = News.query.filter(*a_list).order_by(News.create_time.desc()).paginate(page,per_page,False)
    # 获取到分页对象中的内容
    # 当前在第几页
    currentPage = paginate.page
    # 一共查询到多少页
    totalPage = paginate.pages
    # 查询到的所有对象
    items = paginate.items
    # 将对象列表, 转成字典列表
    cont_list = []
    for cont in items:
        cont_list.append(cont.to_dict())

    # 返回响应, 携带数据
    return jsonify(errno=RET.OK,errmsg="查询成功",totalPage=totalPage,currentPage=currentPage,newsList=cont_list)
